<?php
/**
 * Created by PhpStorm.
 * User: mf
 * Date: 2017/9/5
 * Time: 17:56
 */
namespace app\admin\logic;

use think\Cookie;
use think\Db;
use tool\Common;

class Shoppingcart extends Base
{
    //添加商品到购物车
    public function addProductToPlanBuy()
    {
        $roleID = $this->getRoleID();
        $userID = $this->getUserID();
        if ($roleID != 4 && $roleID != 5) {
            return Common::rm(-2,'对不起，您没有权限操作');
        }
        $check = $this->check(__FUNCTION__);
        if ($check['code'] != 1) {
            return $check;
        }
        if ($this->data['number'] == 0 || $this->data['price'] == 0 || $this->data['totalPrice'] == 0) {
            return Common::rm(-2,'添加失败,请选择商品参数');
        }
        $dbProducts = Db::name('shopping_cart')->where('teamID',$userID)->column('productID');
        if (in_array($this->data['productID'],$dbProducts)) {
            return Common::rm(-2,'添加失败,该商品已添加');
        }
        $ar = [
            'teamID' => $userID,
            'productID' => $this->data['productID'],
            'number' => intval($this->data['number']),
            'price' => $this->data['price'],
            'total' => intval($this->data['number']) * $this->data['price'],
            'addtime' => THINK_START_TIME
        ];
        $res = Db::name('shopping_cart')->insert($ar);
        if ($res) {
            return Common::rm(1,'添加成功');
        }
        return Common::rm(-2,'添加失败');
    }

    //查看购物车列表议价中
    public function getShoppingcartList()
    {
        $roleID = $this->getRoleID();
        $userID = $this->getUserID();
        isset($this->data['status'])?true:Common::json(Common::rm(-2,'请选择查看状态'));
        $where['status'] = $this->data['status'];
        $sql = Db::view('shopping_cart','id,teamID,sellerID,price,number,total,productID,status,addtime')
            ->view('product','name,model','product.id = shopping_cart.productID')
            ->view('product_content', 'titleImage', 'product.id = product_content.productID')
            ->order('shopping_cart.addtime asc');
        if ($roleID == 4 || $roleID == 5) {
            if (isset($this->data['teamID']) && $this->data['teamID']) {
                $userID = $this->data['teamID'];
            }
            $where['teamID'] = $userID;
            $list = $sql->view('user', 'sellerName', 'user.id = shopping_cart.sellerID')->where($where)->select();
        }
        if ($roleID == 2) {
            $where['sellerID'] = $userID;
            $list = $sql->view('user', 'sellerName', 'user.id = shopping_cart.teamID')->where($where)->select();
        }
        if (!$list) {
            return Common::rm(-3, '数据为空');
        }
        $ar = [];
        foreach ($list as $key => $val) {
            if ($roleID == 4 || $roleID == 5) {
                $ar[$val['sellerID']][] = $val;
            } else {
                $ar[$val['teamID']][] = $val;
            }
        }
        $arr = [];
        foreach ($ar as $k => $v) {
            $arr[$k]['sellerName'] = $v[0]['sellerName'];
            foreach ($v as $_k => $_v) {
                $arr[$k]['cart'][$_k]['cartID'] = $_v['id'];
                $arr[$k]['cart'][$_k]['productID'] = $_v['productID'];
                $arr[$k]['cart'][$_k]['sellerID'] = $_v['sellerID'];
                $arr[$k]['cart'][$_k]['productName'] = $_v['name'];
                $arr[$k]['cart'][$_k]['model'] = $_v['model'];
                $arr[$k]['cart'][$_k]['number'] = $_v['number'];
                $arr[$k]['cart'][$_k]['price'] = $_v['price'];
                $arr[$k]['cart'][$_k]['totalPrice'] = $_v['total'];
                $arr[$k]['cart'][$_k]['titleImage'] = json_decode($_v['titleImage'], true)[0];
                $arr[$k]['cart'][$_k]['addtime'] = date('Y-m-d H:i:s',$_v['addtime']);
            }
        }
        $arr = array_reverse($arr);
        return Common::rm(1, '操作成功', [
            'productList' => $arr
        ]);
    }

    //订单之后的产品列表
    public function getContractProductList()
    {
        $roleID = $this->getRoleID();
        $userID = $this->getUserID();
        isset($this->data['status'])?true:Common::json(Common::rm(-2,'请选择查看状态'));
        $where['status'] = $this->data['status'];
        $sql = Db::view('shopping_cart','id,teamID,sellerID,price,number,total,productID,status')
            ->view('contract','numberID,addtime','contract.cartID = shopping_cart.id')
            ->view('product','name,model','product.id = shopping_cart.productID')
            ->view('product_content', 'titleImage', 'product.id = product_content.productID')
            ->order('contract.addtime asc');
        if ($roleID == 4 || $roleID == 5) {
            if (isset($this->data['teamID']) && $this->data['teamID']) {
                $userID = $this->data['teamID'];
            }
            $where['teamID'] = $userID;
            $list = $sql->view('user', 'sellerName', 'user.id = shopping_cart.sellerID')->where($where)->select();
        }
        if ($roleID == 2) {
            $where['sellerID'] = $userID;
            $list = $sql->view('user', 'sellerName', 'user.id = shopping_cart.teamID')->where($where)->select();
        }
        if (!$list) {
            return Common::rm(-3, '数据为空');
        }
        $ar = [];
        foreach ($list as $key => $val) {
            if ($roleID == 4 || $roleID == 5) {
                $ar[$val['sellerID']][] = $val;
            } else {
                $ar[$val['teamID']][] = $val;
            }
        }
        $arr = [];
        foreach ($ar as $k => $v) {
            $arr[$k]['numberID'] = $v[0]['numberID'];
            $arr[$k]['addtime'] = date('Y-m-d H:i:s',$v[0]['addtime']);
            foreach ($v as $_k => $_v) {
                $arr[$k]['cart'][$_k]['cartID'] = $_v['id'];
                $arr[$k]['cart'][$_k]['productID'] = $_v['productID'];
                $arr[$k]['cart'][$_k]['sellerID'] = $_v['sellerID'];
                $arr[$k]['cart'][$_k]['productName'] = $_v['name'];
                $arr[$k]['cart'][$_k]['name'] = $_v['sellerName'];
                $arr[$k]['cart'][$_k]['model'] = $_v['model'];
                $arr[$k]['cart'][$_k]['number'] = $_v['number'];
                $arr[$k]['cart'][$_k]['price'] = $_v['price'];
                $arr[$k]['cart'][$_k]['totalPrice'] = $_v['total'];
                $arr[$k]['cart'][$_k]['titleImage'] = json_decode($_v['titleImage'], true)[0];
            }
        }
        $arr = array_reverse($arr);
        return Common::rm(1, '操作成功', [
            'productList' => $arr
        ]);
    }

    //支队、总队点击议价按钮
    public function bargaining()
    {
        $roleID = $this->getRoleID();
        if ($roleID != 4 && $roleID != 5) {
             return Common::rm(-2,'对不起，您没有权限操作');
        }
        isset($this->data['cartID']) && $this->data['cartID']?false:Common::json(Common::rm(-2,'请选择需要议价的产品'));
        $teamID = $this->getUserID();
        $cartInfo = Db::name('shopping_cart')->where('id',$this->data['cartID'])->find();
        if ($cartInfo['status'] != 0) {
            return Common::rm(-2,'已点击议价按钮');
        }
        if ($cartInfo['teamID'] != $teamID) {
            return Common::rm(-2,'产品选择有误');
        }
        Db::name('shopping_cart')->where('id',$this->data['cartID'])->update(['status' => 1]);
        return Common::rm(1,'点击成功，请您前去议价');
    }

    //商家、支队、总队修改订单信息
    public function revise()
    {
        $roleID = $this->getRoleID();
        if ($roleID != 2 && $roleID != 4 && $roleID != 5) {
            return Common::rm(-2,'对不起，您没有权限操作');
        }
        isset($this->data['cartID']) && $this->data['cartID']?false:Common::json(Common::rm(-2,'请选择需要议价的产品'));
        $cartInfo = Db::name('shopping_cart')->where('id',$this->data['cartID'])->find();
        if ($roleID == 2) {
            isset($this->data['price']) && $this->data['price']?false:Common::json(Common::rm(-2,'请填写产品价格'));
            $ar = [
                'price' => $this->data['price'],
                'total' =>  $this->data['price'] * $cartInfo['number']
            ];
        } else {
            isset($this->data['number']) && $this->data['number']?false:Common::json(Common::rm(-2,'请选择产品数量'));
            $ar = [
                'number' => $this->data['number'],
                'total' =>  $this->data['number'] * $cartInfo['price']
            ];
        }
        Db::name('shopping_cart')->where('id',$this->data['cartID'])->update($ar);
        return Common::rm(1,'修改成功');
    }

    //支队、总队点击确认按钮
    public function confirm()
    {
        $roleID = $this->getRoleID();
        if ($roleID != 4 && $roleID != 5) {
            return Common::rm(-2,'对不起，您没有权限操作');
        }
        isset($this->data['cartID']) && $this->data['cartID']?false:Common::json(Common::rm(-2,'请选择需要确认的产品'));
        $cartInfo = Db::name('shopping_cart')->where('id',$this->data['cartID'])->find();
        if ($cartInfo['status'] == 1) {
            Db::name('shopping_cart')->where('id',$this->data['cartID'])->update(['status' => 2]);
            return Common::rm(1,'确认成功');
        } elseif ($cartInfo['status'] == 2) {
            return Common::rm(-2,'您已确认');
        } else {
            return Common::rm(-2,'确认失败');
        }
    }

    //选择确认的订单生成合同
    public function createContract()
    {
        $userID = $this->getUserID();
        $dbsontract = Db::name('contract')->where('cartID','in',$this->data['cartID'])->find();
        if ($dbsontract) {
            return Common::rm(-2,'合同生成失败,订单已生成合同');
        }
        $timestamp = time();
        $time = date("YmdHis");
        $numberID = $time.$userID;
        $name = 'contract/'.$time.'docx';
        $ar = [];
        foreach ($this->data['cartID'] as $key => $val) {
            $ar[] = [
                'name' => $name,
                'numberID' => $numberID,
                'cartID' => $val,
                'addtime' => $timestamp
            ];
        }
        Db::name('contract')->insertAll($ar);
        return Common::rm(1,'订单生成成功');

        $arr['total'] = 1000;//房屋总套数
        $arr['tfee'] = 19856.88;//服务费
        $arr['buy_start_time'] = date('Y年m月d日',1498838400);//购买开始时间
        $arr['buy_end_time'] = date('Y年m月d日',1504195200);//购买结束时间
        $arr['start_s'] = date('Y年m月d日',1501516800);//业务开始时间
        $arr['end_s'] = date('Y年m月d日',1504108800);//业务开始时间
        $arr['project_name'] = '合肥小猪CMS科技有限公司';//项目名称

        //引入wordphp核心文件
        /*require './ThinkPHP/Library/Vendor/PHPWord/PHPWord.php';
        require './ThinkPHP/Library/Vendor/PHPWord/PHPWord/IOFactory.php';*/

        require VENDOR_PATH.'PHPWord/PHPWord.php';
        require VENDOR_PATH.'PHPWord/PHPWord/IOFactory.php';

        // New Word Document
        $PHPWord = new \PHPWord();

        // New portrait section
        $section = $PHPWord->createSection();

        // Add text elements
        $str = "      ".$arr['project_name']."项目，与腾讯房产于".$arr['buy_start_time']."至".$arr['buy_end_time']."开展腾讯电商团购合作，".$arr['start_s']."至".$arr['end_s']."内，共计售出房屋". $arr['total']."套，成交明细见附件，收取服务费合计".$arr['tfee']."元，特此证明。";

        $str5 = "      本确认函中的房源均已通过网签为确认标准，经双方授权代表签字后生效作为收款确认依据。且一旦签字盖章，乙方将不再承担该房源后续的电商团购费的退款责任。";

        $str1 = "甲    方：                                                          乙    方：";
        $str2 = "授权代表签字：  　                                              授权代表签字：";
        $str3 = "盖章：                                                                  盖章：";
        $str4 = "签约时间：        年        月        日                            签约时间：        年        月        日";

        $title = iconv('utf-8','GB2312//IGNORE','协议供货平台成交签约确认函');//word标题

        $section->addText($title,'rStyle','pStyle');
        $section->addTextBreak(2);
        $section->addText(iconv('utf-8','GB2312//IGNORE',$str),'cOntent');
        $section->addTextBreak(2);
        $section->addText(iconv('utf-8','GB2312//IGNORE',$str5),'cOntent');
        $section->addTextBreak(2);
        $section->addText(iconv('utf-8','GB2312//IGNORE',$str1),'cOntent');
        $section->addText(iconv('utf-8','GB2312//IGNORE',$str2),'cOntent');
        $section->addText(iconv('utf-8','GB2312//IGNORE',$str3),'cOntent');
        $section->addText(iconv('utf-8','GB2312//IGNORE',$str4),'cOntent');
        $section->addTextBreak(2);

        //$section->addText('I am inline styled.', array('name'=>'Verdana', 'color'=>'006699'));
        $section->addTextBreak(2);
        $PHPWord->addFontStyle('cOntent', array('bold'=>false, 'size'=>12));
        $PHPWord->addFontStyle('rStyle', array('bold'=>true, 'italic'=>false, 'size'=>16,'align'=>'center'));
        $PHPWord->addParagraphStyle('pStyle', array('align'=>'center', 'spaceAfter'=>100));
        //$section->addText('I am styled by two style definitions.', 'rStyle', 'pStyle');
        //$section->addText('I have only a paragraph style definition.', null, 'pStyle');

        //Save File
        $objWriter = \PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
        $objWriter->save(config('__PUBLIC__').'contract/'.$time.'.docx');

        // return '/'.date("YmdHis").'.docx';   //返回生成的word文件的路径
        $file = config('__PUBLIC__').'contract/'.$time.'.docx';
        header("Content-type: application/octet-stream");
        header('Content-Disposition: attachment; filename=电商成交确认函.docx');
        header("Content-Length: ". filesize($file));
        readfile($file);
        return Common::rm(1,'合同已生成',$file);
    }

    public function test()
    {
        $file = 'contract/20171019112223.docx';
        header("Content-type: application/octet-stream");
        header('Content-Disposition: attachment; filename=电商成交确认函.docx');
        header("Content-Length: ". filesize($file));
        readfile($file);
        return Common::rm(1,'合同已生成',$file);
    }

    //商家发货按钮（针对一个合同）
    public function sendoutProduct()
    {
        $roleID = $this->getRoleID();
        if (!isset($this->data['numberID']) || !$this->data['numberID']) {
            return Common::rm(-2,'请选择合同');
        }
        $cartIDs = Db::name('contract')->where('numberID',$this->data['numberID'])->column('cartID');
        if ($roleID == 4 || $roleID == 5) {
            $ar = [
                'status' => 6
            ];
            $print = '确认收货';
        }
        if ($roleID == 2) {
            $ar[] = [
                'status' => 4
            ];
            $print = '发货';
        }
        Db::name('shopping_cart')->where('id','in',$cartIDs)->update($ar);
        return Common::rm(1,$print.'成功');
    }
}